<?php

namespace app\mobile\controller;

use app\common\model\RougeSystem;
use app\common\model\RougeSystemWx;
use app\common\model\RougeUser;
use think\Controller;
use think\Session;
use Wechat\WechatApi;

class BaseT extends Controller
{
    public function init($url = '')
    {
        $param = request()->param();
        if (!isset($param['platid'])) {
            $this->error('请刷新页面后重试');
            exit();
        }
        $plat = $param['platid'];
        $openid = Session::get($plat . "_openid");
        $option = $this->option($plat);
        $WxObj = new WechatApi($option);
        $model = new RougeUser();
        if (!$openid) {
            $userinfo = $WxObj->getOauthAccessToken();
            //获取授权为空时向微信发送请求
            if (!$userinfo) {
                $request = request();
                if (!$url) {
                    $url = $request->url(true);
                }
                $callback = $url;
                $url = $WxObj->getOauthRedirect($callback, '', 'snsapi_userinfo');
                header("Location:$url");
                exit();
            } else {
                $openid=$userinfo['openid'];
                Session::set($plat."_openid",$openid);
                $user = $model->where('openid', $openid)->find();
                if (!$user) {
                    $users = $WxObj->getOauthUserinfo($userinfo['access_token'], $openid);
                    if (isset($param['outer'])) {
                        $binding = $this->getbinduser($param['outer']);
                        //获取三级END
                        $data['three_openid'] = $binding['three_openid'];           //三级
                        $data['two_openid'] = $binding['two_openid'];               //二级
                        $data['top_openid'] = $param['outer'];                      //一级
                        $data['type'] = 1;
                    }
                    $data['openid'] = $users['openid'];
                    $data['nickname'] = $users['nickname'];
                    $data['sex'] = $users['sex'];
                    $data['header_url'] = $users['headimgurl'];
                    $data['wx_info'] = json_encode($users, JSON_UNESCAPED_UNICODE);
                    $data['uniacid'] = $plat;
                    $data['create_time'] = time();
                    $model->allowField(true)->save($data);
                    $users['id']=$model->id;
                    $users['uniacid']=$plat;
                }else{
                    $users['id']=$user['id'];
                    $users['uniacid']=$user['uniacid'];
                }
                $users = $model->where('openid', $openid)->find();
                Session::set('user_id', $users['id']);
                Session::set('uniacid', $users['uniacid']);
                $system = new RougeSystem();
                $map['uniacid'] = $users['uniacid'];
                $sysinfo = $system->where($map)->field('title,uniacid')->find();
                $this->assign('sysinfo', $sysinfo);
                //END
                $jssdkconfig = $this->getjssdk();      //
                $jssdksharedata = $this->getsharedata($sysinfo);    //
                $jssdkconfig = json_encode($jssdkconfig);
                $this->assign('jssdkconfig', $jssdkconfig);
                $this->assign('jssdksharedata', $jssdksharedata);
                //获取信息授权END
            }
        }else{
            $users = $model->where('openid', $openid)->find();
            Session::set('user_id', $users['id']);
            Session::set('uniacid', $users['uniacid']);
            $system = new RougeSystem();
            $map['uniacid'] = $users['uniacid'];
            $sysinfo = $system->where($map)->field('title,uniacid')->find();
            $this->assign('sysinfo', $sysinfo);
            //END
            $jssdkconfig = $this->getjssdk();      //
            $jssdksharedata = $this->getsharedata($sysinfo);    //
            $jssdkconfig = json_encode($jssdkconfig);
            $this->assign('jssdkconfig', $jssdkconfig);
            $this->assign('jssdksharedata', $jssdksharedata);
        }
    }

    //获取二级和三级
    private function getbinduser($top_openid = ''){
        $RougeUser = new RougeUser();
        $map['openid'] = $top_openid;
        $two_user = $RougeUser->where($map)->field('top_openid')->find();     //二级
        if ($two_user){
            //END
            $two_openid = $two_user['top_openid'];
            $map1['openid'] = $two_user['top_openid'];
            $three_user = $RougeUser->where($map1)->field('top_openid')->find();       //三级
            if ($three_user){
                //END
                $three_openid = $three_user['top_openid'];
            }else{
                $three_openid = '';
            }
        }else{
            $two_openid = '';
        }
        $data['two_openid'] = $two_openid;
        $data['three_openid'] = $three_openid;
        return $data;
    }


    public function getuserinfo()
    {
        $RougeUser = new RougeUser();
        $se = Session::get();
        $map['uniacid'] = $se['uniacid'];
        $map['id'] = $se['user_id'];
        $user = $RougeUser->where($map)->find();
        return $user;
    }

    public function getopacid()
    {

    }


    public function getorderno()
    {
        $order = date('YmdHis') . rand(10000, 99999);
        return $order;
    }

    //获取订单
    public function getorder2($sh = 666)
    {
        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
        return $order;
    }


    public function getjssdk()
    {
        $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options();
        //分享
        $weObj = new WechatApi($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' => $jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'openAddress', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice',
                'pauseVoice' . 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation',
                'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView'
            ]
        ];
        return $wxJsSdk;
    }

    public function getsharedata($param)
    {
        $data = [
            'title' => $param['title'] . "- IOS版",
            'desc' => "连续闯三关专柜/官网口红送到家",
            'link' => request()->domain() . '/mobile.php/login/index/platid/' . $param['uniacid']

        ];
        return $data;
    }

    //微信API参数  根据card_id获取
    /*
     * $card_id
     */
    public function option($plat)
    {
        //  Session::set('openid', null);
        $model = new RougeSystemWx();
        $mab['uniacid'] = $plat;
        $users = $model->where($mab)->field('appid,appsecret,token,encodingaeskey')->find();
        $options = array(
            'appid' => $users['appid'], // 填写高级调用功能的app id
            'appsecret' => $users['appsecret'], // 填写高级调用功能的密钥
            'token' => $users['token'], // 填写你设定的key
            'encodingaeskey' => $users['encodingaeskey'], // 填写加密用的EncodingAESKey
        );
        return $options;
    }

    //微信API参数  根据card_id获取
    /*
     * $card_id
     */
    public function options()
    {
        //  Session::set('openid', null);
        $model = new RougeSystemWx();
        $mab['uniacid'] = Session::get('uniacid');
        $users = $model->where($mab)->field('appid,appsecret,token,encodingaeskey,mch_id,partnerkey')->find();
        $options = array(
            'appid' => $users['appid'], // 填写高级调用功能的app id
            'mch_id' => $users['mch_id'], // 填写高级调用功能的app id
            'partnerkey' => $users['partnerkey'], // 填写高级调用功能的app id
            'appsecret' => $users['appsecret'], // 填写高级调用功能的密钥
            'token' => $users['token'], // 填写你设定的key
            'encodingaeskey' => $users['encodingaeskey'], // 填写加密用的EncodingAESKey
        );
        return $options;
    }
}
